<?php
/**
 * Created by Command.
 * User: Vito
 */

namespace app\admin\curd\room_lease_record;

use think\helper\Str;
use app\common\curd\Save;
use app\logic\UserLogic;
use think\facade\Request;
use app\logic\RoomLeaseRecordLogic;
use app\exception\MessageException;
class RoomLeaseRecordSave extends Save
{
    //验证器
    protected $validate = [];
    //追加数据
    protected $appendParams = [];
    //允许新增的数据字段
    protected $field = [];

    /**
     * @Description: 重写入住申请
     * @author: xiayu <cb1071403016@126.com>
     * @param [type] $next
     * @param [type] $params
     * @Date: 2022-10-25 09:30:02
     * @version: 1.0.0
     * @return [type]
     */    
    protected function saveMiddleware($next, $params){
        
        // $response = $next($params);

        $user = new UserLogic;
        $RoomLeaseRecordLogic = new RoomLeaseRecordLogic;

        $is_user = $this->findUser($params);
        if(!$params['avatar']){
            $params['avatar'] = 'http://121.5.189.38:8012/upload/attachment/08/9ddbabd7d7c2180f52b649e7945ba7.png';
        }
        // 当用户存在时，进入该流程
        if($is_user){
            
            $userWhere['id'] = $is_user['id'];
            $saveData = [
                'avatar'=> $is_user['avatar'],
                // 'mark'  => $is_user['mark']
            ];

            $user->saveUser($userWhere,$saveData);

            // $RoomLeaseRecordLogic->addRecord($is_user);
            $params['user_id'] = $is_user['id'];

            return $next($params);
        }
        // 用户不存在时，进行注册用户流程
        $random = Str::random(10);
        $params['username'] = 'tourist_' . $random;
        $params['password'] = 'a123456.';
        $params['nickname'] = '游客' . $random;
        $params['platform'] = 9;
        $params['add_ip']   = Request::ip();
        $params['flow']     = config('web.is_dev') ? 100 : 0;
        
       
        $res = $user->register($params);


        $params['user_id'] = $res['id'];
        // $RoomLeaseRecordLogic->addRecord($res);

        // $this->saveMiddleware1($res);

        return $next($params);
    }
    /**
     * @Description: 查找用户是否存在
     * @author: xiayu <cb1071403016@126.com>
     * @param [type] $params
     * @Date: 2022-10-25 09:29:40
     * @version: 1.0.0
     * @return [type]
     */
    protected function findUser($params)
    {
         $user = new UserLogic;

         $where['tel'] = $params['tel'];

         $res = $user->findUser($where);
         
         $where['sex']          = $params['sex'];
         $where['real_name']    = $params['real_name'];
         $where['id_card']      = $params['id_card'];
         $where['word_unit']    = $params['word_unit']; 

         if($res){

            $findUser = $user->findUser($where);

            if(!$findUser){
                throw new MessageException('用户已存在,且与用户录入的信息不匹配,请联系管理员修改用户信息');
            }

            return $res;
            
         }

         return false;
    }
}